package com.yang.crawler.thread;


import com.yang.crawler.thread.manager.ThreadPoolMonitorManager;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ApplicationContextEvent;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.core.Ordered;

public class ThreadContext implements ApplicationListener<ApplicationContextEvent>, Ordered {
    private static ThreadContext instance;

    private ApplicationContext applicationContext;

    public static ApplicationContext getApplicationContext() {
        return instance.applicationContext;
    }

    @Override
    public void onApplicationEvent(ApplicationContextEvent event) {
        if (event instanceof ContextRefreshedEvent) {
            // 初始化上下文
            ThreadContext.instance = this;
            instance.applicationContext = applicationContext;
        } else if (event instanceof ContextClosedEvent) {
            System.out.println("销毁了=======");
            shutdown();
        }
    }

    private void shutdown() {
        ThreadPoolMonitorManager.shutdown();
    }

    @Override
    public int getOrder() {
        return 30;
    }
}

